/*
 * @Description: app actions
 * @Author: ZY
 * @Date: 2020-12-23 10:25:37
 * @LastEditors: scy😊
 * @LastEditTime: 2021-01-29 08:46:37
 */
import {ActionTree, ActionContext} from 'vuex'
import {RootState, useStore} from '@/store'
import {state, UserState} from './state'
import {Mutations} from './mutations'
import {UserMutationTypes} from './mutation-types'
import {UserActionTypes} from './action-types'
// import { loginRequest, userInfoRequest } from '@/apis/user'
import {doLogin, getCurrUser, LoginParam} from '@/services/login-service';
import {listByCurrUser} from "@/services/system/menu";
import {removeToken, setToken, setRefreshToken, getRefreshToken} from '@/utils/cookies'
// import { PermissionActionType } from '../permission/action-types'
import router, {resetRouter} from '@/router'
import {RouteRecordRaw} from 'vue-router'
import {el} from 'element-plus/es/locale'

import {ElMessage} from "element-plus";

type AugmentedActionContext = {
  commit<K extends keyof Mutations>(
    key: K,
    payload: Parameters<Mutations[K]>[1],
  ): ReturnType<Mutations[K]>
} & Omit<ActionContext<UserState, RootState>, 'commit'>

export interface Actions {
  [UserActionTypes.ACTION_LOGIN](
    {commit}: AugmentedActionContext,
    userInfo: any
  ): void

  [UserActionTypes.ACTION_RESET_TOKEN](
    {commit}: AugmentedActionContext
  ): void

  [UserActionTypes.ACTION_GET_USER_INFO](
    {commit}: AugmentedActionContext
  ): void

  [UserActionTypes.ACTION_GET_ROUTER_LIST](
    {commit}: AugmentedActionContext
  ): void


  [UserActionTypes.ACTION_CHANGE_ROLES](
    {commit}: AugmentedActionContext, role: string
  ): void

  [UserActionTypes.ACTION_LOGIN_OUT](
    {commit}: AugmentedActionContext,
  ): void


  [UserActionTypes.ACTION_SET_CURRENT_DATA_SOURCE](
    {commit}: AugmentedActionContext,
    userInfo: object
  ): void

  [UserActionTypes.ACTION_SET_IS_SHOW_COLOR](
    {commit}: AugmentedActionContext,
    event: boolean
  ): void

  [UserActionTypes.ACTION_BREAD_CRUMB_LIST](
    {commit}: AugmentedActionContext,
    event: any
  ): void

  [UserActionTypes.ACTION_GET_JUMP_LOADING](
    {commit}: AugmentedActionContext,
    event: any
  ): void
}

export const actions: ActionTree<UserState, RootState> & Actions = {
  async [UserActionTypes.ACTION_LOGIN](
    {commit}: AugmentedActionContext,
    userInfo: any
  ) {
    let {username} = userInfo
    username = username?.trim()
    console.log(userInfo);

    return new Promise((resolve, reject) => {
      doLogin(userInfo).then(async (res: any) => {
        console.log(res);
        
        if (res?.code === 200 && res.data.access_token) {
        const {access_token, token_type, refresh_token} = res.data;
        const accessToken = token_type + ' ' + access_token;
        setToken(accessToken)
        setRefreshToken(refresh_token);
        commit(UserMutationTypes.SET_TOKEN, accessToken)
        commit(UserMutationTypes.SET_REFRESH_TOKEN, refresh_token)
        console.log(res);
        resolve(res)
        }else{
          ElMessage.error(res.msg)
          reject(res.msg)  
        }
      }).catch((err:any) => {
        console.log(err);
        // ElMessage.error(err)
        reject(err) 
        })
    })
    // await doLogin(userInfo).then(async(res:any) => {
    //   if (res?.code === 200 && res.data.access_token) {
    //     const {access_token, token_type, refresh_token} = res.data;
    //     const accessToken = token_type + ' ' + access_token;
    //     setToken(accessToken)
    //     setRefreshToken(refresh_token);
    //     commit(UserMutationTypes.SET_TOKEN, accessToken)
    //     commit(UserMutationTypes.SET_REFRESH_TOKEN, refresh_token)
    //   }
    // }).catch((err:any) => {
    //   console.log(err)
    // })
  },
  [UserActionTypes.ACTION_REFRESH_TOKEN]({commit}: AugmentedActionContext) {
    return new Promise((resolve, reject) => {
      //获取 refresh_token
      const req = {grant_type: 'refresh_token', refresh_token: getRefreshToken()} as LoginParam;
      doLogin(req).then(async ({data}) => {
        const {access_token, token_type, refresh_token} = data;
        const accessToken = token_type + ' ' + access_token;
        console.log(accessToken);
        //重现赋值token
        setToken(accessToken);
        setRefreshToken(refresh_token);
        commit(UserMutationTypes.SET_TOKEN, accessToken)
        commit(UserMutationTypes.SET_REFRESH_TOKEN, refresh_token)
        resolve(accessToken);
      }).catch(error => {
        reject(error)
      })
    })
  },

  [UserActionTypes.ACTION_RESET_TOKEN](
    {commit}: AugmentedActionContext) {
    removeToken()
    commit(UserMutationTypes.SET_TOKEN, '')
    commit(UserMutationTypes.SET_ROLES, [])
  },

  [UserActionTypes.ACTION_GET_JUMP_LOADING](
    {commit}: AugmentedActionContext, event: boolean) {
    commit(UserMutationTypes.SET_JUMP_LOADING, event)
  },


  async [UserActionTypes.ACTION_GET_USER_INFO](
    {commit}: AugmentedActionContext
  ) {
    if (state.token === '') {
      throw Error('token is undefined!')
    }
    await getCurrUser().then((res: any) => {
      if (res?.code === 200) {
        console.log(res);

        commit(UserMutationTypes.SET_ROLES, res.data.roles)
        commit(UserMutationTypes.IS_ADMIN, res.data.roles?.filter((role: string) => role == 'sysadmin' || role == 'administrator')?.length > 0)
        commit(UserMutationTypes.TENANT_NAME, res.data.tenantName)
        commit(UserMutationTypes.CURRENT_USER, res.data)
        commit(UserMutationTypes.SET_NAME, res.data.name)
        // commit(UserMutationTypes.SET_AVATAR, res.data.avatar)
        // commit(UserMutationTypes.SET_INTRODUCTION, res.data.introduction)
        // commit(UserMutationTypes.SET_EMAIL, res.data.email)
        return res
      } else {
        throw Error('Verification failed, please Login again.')
      }
    })
  },


  async [UserActionTypes.ACTION_GET_ROUTER_LIST](
    {commit}: AugmentedActionContext
  ) {
    if (state.token === '') {
      throw Error('token is undefined!')
    }
    await listByCurrUser().then((res: any) => {
      if (res?.code === 200) {
        console.log(res);
        commit(UserMutationTypes.SET_ROUTER_LIST, res.data)
        return res
      } else {
        throw Error('Verification failed, please Login again.')
      }
    })
  },




  async [UserActionTypes.ACTION_CHANGE_ROLES](
    {commit}: AugmentedActionContext,
    role: string
  ) {
    // const token = role + '-token'
    // const store = useStore()
    // commit(UserMutationTypes.SET_TOKEN, token)
    // setToken(token)
    // await store.dispatch(UserActionTypes.ACTION_GET_USER_INFO, undefined)
    // store.dispatch(PermissionActionType.ACTION_SET_ROUTES, state.roles)
    // store.state.permission.dynamicRoutes.forEach((item: RouteRecordRaw) => {
    //   router.addRoute(item)
    // })
  },

  [UserActionTypes.ACTION_LOGIN_OUT](
    {commit}: AugmentedActionContext
  ) {
      console.log(commit)
      removeToken()
      commit(UserMutationTypes.SET_ROUTER_LIST,[])
      commit(UserMutationTypes.SET_TOKEN, '')
      commit(UserMutationTypes.SET_ROLES, [])
      commit(UserMutationTypes.IS_ADMIN, false)
      commit(UserMutationTypes.TENANT_NAME, '')
      commit(UserMutationTypes.CURRENT_USER, {})
      commit(UserMutationTypes.SET_NAME, '')
      commit(UserMutationTypes.SET_REFRESH_TOKEN, '')
      resetRouter()
  },

  [UserActionTypes.ACTION_SET_CURRENT_DATA_SOURCE](
    {commit}: AugmentedActionContext, userInfo: object) {
    console.log(userInfo);

    commit(UserMutationTypes.SET_CURRENT_DATA_SOURCE, userInfo)
  },

  [UserActionTypes.ACTION_SET_IS_SHOW_COLOR](
    {commit}: AugmentedActionContext, event: boolean) {
    commit(UserMutationTypes.SET_IS_SHOW_COLOR, event)
  },

  [UserActionTypes.ACTION_BREAD_CRUMB_LIST](
    {commit}: AugmentedActionContext, event: any) {
    commit(UserMutationTypes.SET_BREAD_CRUMB_LIST, event)
  },

}
